﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace Ooaavee.Support
{
    /// <summary>
    /// This class exposes static methods for serialization routines.
    /// </summary>
    public static class Serializer
    {
        /// <summary>
        /// Converts a data contract object to a xml string.
        /// </summary>
        /// <typeparam name="TDataContract">Data contract type.</typeparam>
        /// <param name="obj">The data contract object to convert.</param>
        /// <returns>The result of conversion.</returns>
        public static string SerializeDataContract<TDataContract>(TDataContract obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            using (var backing = new StringWriter())
            {
                using (var writer = new XmlTextWriter(backing))
                {
                    GetDataContractSerializer(typeof(TDataContract)).WriteObject(writer, obj);
                    return backing.ToString();
                }
            }            
        }

        /// <summary>
        /// Converts a xml string to a data contract object.
        /// </summary>
        /// <typeparam name="TDateContract">Data contract type.</typeparam>
        /// <param name="xml">The xml string to convert.</param>
        /// <returns>The result of conversion.</returns>
        public static TDateContract DeserializeDataContract<TDateContract>(string xml)
        {
            if (xml == null)
            {
                throw new ArgumentNullException("xml");
            }

            using (var backing = new StringReader(xml))
            {
                using (var reader = new XmlTextReader(backing))
                {
                    return (TDateContract)GetDataContractSerializer(typeof(TDateContract)).ReadObject(reader);
                }
            }            
        }

        private static DataContractSerializer GetDataContractSerializer(Type type)
        {
            return new DataContractSerializer(type,
                                              new List<Type>(),
                                              int.MaxValue,
                                              true,
                                              true,
                                              null);
        }        

    }
}
